package com.ocean.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocean.admin.entity.SysDictData;
import com.ocean.admin.entity.SysDictType;
import com.ocean.admin.extension.ConstantsCacheExtension;
import com.ocean.admin.extension.security.core.SysUserDetails;
import com.ocean.admin.extension.security.filter.WebFilterExtend;
import com.ocean.admin.mapper.SysDictTypeMapper;
import com.ocean.admin.model.dto.dictype.SysDictTypeQueryDTO;
import com.ocean.admin.model.dto.dictype.SysDictTypeSaveDTO;
import com.ocean.admin.model.dto.dictype.SysDictTypeUpdateDTO;
import com.ocean.admin.model.vo.dictype.SysDictTypeSelectVo;
import com.ocean.admin.model.vo.dictype.SysDictTypeVo;
import com.ocean.admin.service.ISysDictDataService;
import com.ocean.admin.service.ISysDictTypeService;
import com.ocean.cache.redis.IRedisCache;
import com.ocean.core.exception.verify.ApplicationException;
import com.ocean.core.util.constants.ConstantsAttribute;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典类型表 服务实现类
 * </p>
 *
 * @author zhang
 * @since 2022-08-16
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {

    @Autowired
    private ISysDictDataService iSysDictDataService;

    /**
     * 分页查询字典类型
     *
     * @param queryDTO 查询条件
     * @return 结果
     */
    @Override
    public IPage<SysDictTypeVo> pageList(SysDictTypeQueryDTO queryDTO) {
        Page<SysDictTypeVo> page = new Page<>(queryDTO.getPage(), queryDTO.getPageSize());
        IPage<SysDictTypeVo> pageList = baseMapper.pageList(page, queryDTO);
        pageList.getRecords().forEach(res -> res.setStatusName(res.getStatus() == 1 ? "停用" : "正常"));
        return pageList;
    }

    /**
     * 新增字典类型
     *
     * @param saveDTO 字典类型
     * @return 结果
     */
    @Override
    public String saveDicType(SysDictTypeSaveDTO saveDTO) {
        SysDictType type = new SysDictType();
        BeanUtils.copyProperties(saveDTO, type);
        SysUserDetails current = WebFilterExtend.current();
        type.setCreateUserId(current.getUserId());
        type.setCreateUserName(current.getNickName());
        type.setUpdateUserId(current.getUserId());
        type.setUpdateUserName(current.getNickName());
        this.save(type);
        return ConstantsAttribute.INSERT_SUCCESS;
    }

    /**
     * 修改字典类型
     *
     * @param updateDTO 字典类型
     * @return 结果
     */
    @Override
    public String updateDicType(SysDictTypeUpdateDTO updateDTO) {
        SysDictType type = new SysDictType();
        BeanUtils.copyProperties(updateDTO, type);
        SysUserDetails current = WebFilterExtend.current();
        type.setUpdateUserId(current.getUserId());
        type.setUpdateUserName(current.getNickName());
        this.updateById(type);
        return ConstantsAttribute.UPDATE_SUCCESS;
    }

    /**
     * 删除字典类型
     *
     * @param dictIds 字典类型ID
     * @return 结果
     */
    @Override
    public String removeDicType(Long[] dictIds) {
        List<Long> dicList = Arrays.asList(dictIds);
        List<SysDictType> dictTypeList = this.listByIds(dicList);
        List<String> collect = dictTypeList.stream().map(SysDictType::getDictType).collect(Collectors.toList());
        long count = iSysDictDataService.count(Wrappers.<SysDictData>lambdaQuery().in(SysDictData::getDictType,
                collect));
        if (count > 0) {
            throw new ApplicationException("所选中的字典中还有子字典，无法删除");
        }
        this.removeByIds(dicList);
        return ConstantsAttribute.REMOVE_SUCCESS;
    }

    /**
     * 获取字典选择框列表
     *
     * @return 结果
     */
    @Override
    public List<SysDictTypeSelectVo> optionSelect() {
        return baseMapper.selectOptionSelect();
    }
}

@Configuration
class ApplicationListener implements ApplicationRunner, Ordered {

    @Autowired
    private ISysDictDataService iSysDictDataService;

    @Autowired
    private IRedisCache iRedisCache;

    @Override
    public void run(ApplicationArguments args) {
        Map<String, List<SysDictData>> dictDataMap = iSysDictDataService.list().stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) {
            iRedisCache.set(ConstantsCacheExtension.getInstance().getDicCache() + entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList()));
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
